<!--
 * @Description: 地图
 * @Author: Ronda
 * @Date: 2022-02-16 09:30:06
 * @LastEditors: Ronda
 * @LastEditTime: 2022-05-23 15:25:47
-->
<template>
  <div>
    <div class="map-wrapper"  style="width: 100%;">
      <!-- 加载状态提示 -->
      <div v-if="mapLoading" class="map-loading">地图加载中...</div>
      <div v-if="mapError" class="map-error">地图加载失败，请刷新重试</div>
      
      <!-- 地图容器 -->
      <div ref="mapCanvas" class="map-container"></div>
    </div>
  </div>
</template>

<script>
import { get } from '@/utils/request';
import { mapMutations, mapState } from 'vuex';
import AMapLoader from '@amap/amap-jsapi-loader'; // 新增导入

export default {
  data() {
    return {
      empData:[],
      map: null,
      mapLoading: true,
      mapError: false,
      markers: [],
      polygons: [] // 新增：存储行政区划多边形实例
    };
  },
  props: {
    empData: {
      type: Array,
      default: () => []
    }
  },
  watch: {
    empData: {
      immediate: true,
      handler(newVal) {
        if (this.map) {
          this.clearMarkers();
          this.addMarkers(newVal);
        }
      }
    }
  },
  methods: {
    ...mapMutations(['SET_ED']),
    async loadMap() {
      try {
        // 配置安全密钥
        window._AMapSecurityConfig = {
          securityJsCode: '9ecc1d834b875646aa8587e2dc5a02a0' // 请替换为实际安全密钥
        };

        const AMap = await AMapLoader.load({
          key: "71508ef2780a6c03ecabc227037e64c1",
          version: "2.0",
        });

        this.initMap(AMap);
        this.loadDistrictBoundary(AMap); // 新增：加载行政区划边界
      } catch (e) {
        console.error('地图加载失败:', e);
        this.mapError = true;
      } finally {
        this.mapLoading = false;
      }
    },
    async loadEmpData() {
            let res = await get('/dashboard/findEngineerDeviceTree');
            let temp = [];
            res.data.forEach((item, index, arr) => {
                if (item.children.length > 0) {
                    item.children.forEach(it => {
                        temp.push(it)
                    })
                }
            });
            // console.log(temp,'22222');
            this.empData = temp;
        },
    
    initMap(AMap) {
      if (!this.$refs.mapCanvas) return;

      this.map = new AMap.Map(this.$refs.mapCanvas, {
        pitch: 50, // 新增：俯仰角度
        viewMode: '3D', // 新增：3D 模式
        rotateEnable: true,
        pitchEnable: true,
        zoom: 17,
        rotation: -15, // 新增：初始旋转角度
        center: [103.828434, 36.064822],
        mapStyle: 'amap://styles/normal',
      });
      // 添加控件
      AMap.plugin(['AMap.ToolBar', 'AMap.Scale'], () => {
        this.map.addControl(new AMap.ToolBar());
        this.map.addControl(new AMap.Scale());
      });
      // this.addMarkers(this.empData);
    },
    loadDistrictBoundary(AMap) {
      AMap.plugin("AMap.DistrictSearch", () => {
        const district = new AMap.DistrictSearch({
          subdistrict: 0,
          extensions: "all",
          level: "district"
        });

        district.search("兰州市", (status, result) => {
          this.clearPolygons(); // 清除旧边界
          
          const bounds = result.districtList[0]?.boundaries;
          if (!bounds) return;

          this.polygons = bounds.map(boundary => new AMap.Polygon({
            strokeWeight: 5,
            path: boundary,
            fillOpacity: 0.4,
            fillColor: "#80d8ff",
            strokeColor: "#0091ea",
          }));

          this.map.add(this.polygons);
          this.map.setFitView(this.polygons);
        });
      });
    },

    addMarkers(data) {
      const validData = data.filter(item => 
        this.isValidCoordinate(item.position)
      );

      validData.forEach(item => {
        const marker = new AMap.Marker({
          position: item.position,
          title: item.name,
          extData: item,
          content: this.createMarkerContent(item.status) // 根据状态生成不同样式
        });

        marker.on('click', () => {
          // 修改：调用 mutation 替代 emit
          this.SET_ED({
            device_id: item.id,
            engineer_id: item.engineer_id
          });
          this.map.setCenter(item.position);
        });

        this.markers.push(marker);
      });

      this.map.add(this.markers);
      if (validData.length > 0)this.map.setFitView();
    },

    

    isValidCoordinate(position) {
      if (!position || !Array.isArray(position)) return false;
      const [lng, lat] = position.map(Number);
      return !isNaN(lng) && !isNaN(lat) && 
             lng >= 73 && lng <= 135 && 
             lat >= 3 && lat <= 53;
    },

    createMarkerContent(status) {
      // 根据设备状态生成不同颜色的标记
      const color = status === 1 ? '#00ff00' : '#ff0000';
      return `<div style="
        width: 20px;
        height: 20px;
        background: ${color};
        border-radius: 50%;
        border: 2px solid white;
        box-shadow: 0 2px 5px rgba(0,0,0,0.3);
      "></div>`;
    },

    clearMarkers() {
      if (this.map) {
        this.map.remove(this.markers);
      }
      this.markers = [];
    },
    clearPolygons() {
      if (this.map && this.polygons.length) {
        this.map.remove(this.polygons);
      }
      this.polygons = [];
    },
  },
  async mounted() {
    await this.loadMap();
    await this.loadEmpData();
  },
  beforeDestroy() {
    if (this.map) {
      this.map.destroy();
      this.clearPolygons();
    }
  }
};
</script>
<style scoped>
.map-wrapper {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
}

.map-container {
  width: 100%;
  height: 100%;
  display: block;

}
.map-loading, .map-error {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  padding: 10px 20px;
  background: rgba(0,0,0,0.7);
  color: white;
  border-radius: 4px;
  z-index: 999;
}
</style>